package com.androider.timememory.sms;

import java.util.ArrayList;
import java.util.HashMap;

import com.androider.timememory.R;
import com.androider.timememory.activity.Album;
import com.androider.timememory.db.RecordModel;
import com.androider.timememory.sms.SMS;
import com.androider.timememory.utils.Constants;
import com.androider.timememory.utils.SMSUtil;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class SMSHandler extends Handler {
	public static final String TAG = "SMSHandler";
	
	private Context mContext;
	
	public SMSHandler(Context context) {
		this.mContext = context;
	}
	
	@Override
	public void handleMessage(Message msg) {
		SMS sms = (SMS) msg.obj;
		if(sms.getBody().indexOf(" @TimeMemory.") >= 0){
			Uri uri = Uri.parse(SMSUtil.CONTENT_INBOX + sms.getThreadId());
			mContext.getContentResolver().delete(uri, "_id = " + sms.getId(), null);
			Log.i(TAG, "delete sms, Body:" + sms.getBody());
			
			Boolean isFind = false;
			ArrayList<HashMap<String, Object>> whiteList = RecordModel.getWhiteList(mContext);
			int i=0;
			for(; i<whiteList.size(); i++){
				if(sms.getAddress().equals(whiteList.get(i).get("number"))){
					isFind = true;
					break;
				}
			}
			if(!isFind){
				Log.i(TAG, "handleMessage, not find in whitelist");
				return;
			}
			
			final String appName = mContext.getResources().getString(R.string.app_name);
			final int strIndex = sms.getBody().indexOf(" { ");
			Log.i(TAG, String.format("strIndex:%d", strIndex));
			if(strIndex <= 0){
				return;
			}
			final String searchStr = sms.getBody().substring(strIndex + 3, sms.getBody().length() - 1);
			final String showStr = String.format("来自%s的“%s”：“%s”",(String)whiteList.get(i).get("name"), appName, searchStr);
			
			NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification notification = new Notification(R.drawable.icon, showStr,
					System.currentTimeMillis());
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			notification.defaults = Notification.DEFAULT_SOUND;
			
			Intent intent = new Intent(mContext, Album.class);
			intent.putExtra(Album.ALBUM_DATA_TYPE, Album.ALBUM_DATA_TYPE_SEARCH);
			intent.putExtra(Album.ALBUM_SEARCH_STR, searchStr);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

			PendingIntent contentIntent = PendingIntent.getActivity(mContext,
					R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.setLatestEventInfo(mContext, appName, showStr,
					contentIntent);
			nm.notify(R.string.app_name, notification);
		}
		
	}
}
